package com.jhd.fuzhou.view.photo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.github.barteksc.pdfviewer.util.FitPolicy;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.EPrinterService;
import com.jhd.fuzhou.service.PrinterService;
import com.jhd.fuzhou.util.UploadFile;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.vo.SuperviseEnclosureVo;
import com.jhd.fuzhou.vo.SupervisionInspectionPhotoVo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class ShowPhotoActivity extends BaseActivity {
    @BindView(R.id.tv_title)TextView tv_title;//图片的编号
    @BindView(R.id.tv_delete)TextView tv_delete;//删除图片
    @BindView(R.id.btn_print)Button btn_print;//打印按钮
    @BindView(R.id.pdfView) PDFView pdfView;//显示文书
    private PrinterService printerService;
    private EPrinterService ePrinterService;
    private String supervisionType;
    private int position;
    private Context context=this;
    private ProgressDialog _dialog;
    private List<SupervisionInspectionPhotoVo> supervisionInspectionPhotoVoList;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_show_photo);
    }

    @Override
    protected void processLogic() {
        onBack();
        if(UtilHelper.ePrinterType==0){
            printerService = new PrinterService.Builder(this).build();
        }else{
            ePrinterService=new EPrinterService.Builder(this).build();
        }
        supervisionType=getIntent().getStringExtra("supervisionType");
        supervisionInspectionPhotoVoList=supervisionInspectionVo.getSupervisionInspectionPhotoVoList();
        String s=getIntent().getStringExtra("position");
        position=Integer.valueOf(s);
        new Thread(){
            @Override
            public void run() {
                super.run();
                tv_title.setText(supervisionInspectionPhotoVoList.get(position).getPhotoNum());
                List<SuperviseEnclosureVo> superviseEnclosureVoList;
                if(supervisionType.equals("专项监督")){
                    superviseEnclosureVoList= supervisionInspectionVo.getDocumentAttachmentList();
                }else{
                    superviseEnclosureVoList= supervisionInspectionVo.getSuperviseEnclosureVoList();
                }
                if(superviseEnclosureVoList!=null){
                    for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                        if(superviseEnclosureVo.getEnclosureName().equals("现场照片证据"+supervisionInspectionPhotoVoList.get(position).getPhotoNum())){
                            getUrlPdf(superviseEnclosureVo.getEnclosureUrl());
                            break;
                        }
                    }
                }
            }
        }.start();
        _dialog = new ProgressDialog(context);
        _dialog.setMessage("正在生成图片文书,请稍等...");
        _dialog.show();
    }

    @OnClick({R.id.btn_download, R.id.btn_print, R.id.tv_delete})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_download:
                UploadFile.copyFile(getExternalFilesDir(null).getPath() + "/Download/document.pdf",
                        getExternalFilesDir(null).getPath() + "/Download/"+supervisionType+"/", supervisionInspectionVo.getSupervisedUnitName() + "监督意见书" + ".pdf", context);
                break;
            case R.id.btn_print:
                if(UtilHelper.ePrinterType==0) {
                    printerService.executePrint(btn_print);
                }else {
                    ePrinterService.executePrint(btn_print);
                }
                break;
            case R.id.tv_delete:
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("删除");
                builder.setMessage("你确定删除该现场图片证据吗");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String path=context.getExternalFilesDir(null).getPath() + "/Download/photo/"+supervisionInspectionPhotoVoList.get(position).getPhotoNum()+".png";
                        List<SuperviseEnclosureVo> superviseEnclosureVoList;
                        if(supervisionType.equals("专项监督")){
                            superviseEnclosureVoList= supervisionInspectionVo.getDocumentAttachmentList();
                        }else{
                            superviseEnclosureVoList= supervisionInspectionVo.getSuperviseEnclosureVoList();
                        }
                        if(superviseEnclosureVoList!=null){
                            for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                                if(superviseEnclosureVo.getEnclosureName().equals("现场照片证据"+supervisionInspectionPhotoVoList.get(position).getPhotoNum())){
                                    superviseEnclosureVoList.remove(superviseEnclosureVo);
                                    (new File(path)).delete();
                                    break;
                                }
                            }
                        }
                        if(supervisionType.equals("专项监督")){
                            supervisionInspectionVo.setDocumentAttachmentList(superviseEnclosureVoList);
                        }else{
                            supervisionInspectionVo.setSuperviseEnclosureVoList(superviseEnclosureVoList);
                        }
                        supervisionInspectionPhotoVoList.remove(position);
                        supervisionInspectionVo.setSupervisionInspectionPhotoVoList(supervisionInspectionPhotoVoList);//删除照片
                        dialog.dismiss();
                        finish();
                    }

                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                Dialog dialog = builder.create();
                if (!((Activity) context).isFinishing()) dialog.show();

                int color = context.getResources().getColor(R.color.header);
                Button btn = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
                Button btn2 = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
                if (btn != null) btn.setTextColor(color);
                if (btn2 != null) btn2.setTextColor(color);
                break;
        }
    }
    /*根据url下载pdf*/
    public void getUrlPdf(String url) {
        try {
            URL picurl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) picurl
                    .openConnection();
            conn.setConnectTimeout(6000);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.connect();
            InputStream is = conn.getInputStream();String fileName = "Download/show.pdf";//文件名
            File dir = new File(getExternalFilesDir(null).getPath() + "/Download/");//路径
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(getExternalFilesDir(null).getPath() + "/" + fileName);
            try {
                int index;
                byte[] bytes = new byte[1024];
                FileOutputStream outputStream = new FileOutputStream(file);
                while ((index = is.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, index);
                }
                outputStream.flush();
                outputStream.close();
                is.close();
                handler.sendEmptyMessage(1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    File file = new File(getExternalFilesDir(null).getPath() + "/Download/show.pdf" );
                    showPDF(pdfView,file,context);
                    if (_dialog != null) _dialog.cancel();
                    break;
            }

        }
    };

    public static void showPDF(PDFView pdfView, File file, Context context){
        try {
            pdfView.fromStream(new FileInputStream(file))
                    .enableSwipe(true)
                    .swipeHorizontal(false)
                    .enableDoubletap(true)
                    .defaultPage(0)
                    .enableAnnotationRendering(false)
                    .password(null)
                    .scrollHandle(new DefaultScrollHandle(context))
                    .enableAntialiasing(true)
                    .spacing(0)
                    .autoSpacing(false)
                    .pageFitPolicy(FitPolicy.WIDTH)
                    .fitEachPage(false)
                    .pageSnap(false)
                    .pageFling(false)
                    .nightMode(false)
                    .load();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}